package cn.itcast.demo6.service.impl;

import cn.itcast.demo6.mapper.PurseLogMapper;
import cn.itcast.demo6.mapper.PurseMapper;
import cn.itcast.demo6.pojo.Purse;
import cn.itcast.demo6.pojo.PurseLog;
import cn.itcast.demo6.service.PurseService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * ClassName: PurseServiceImpl
 * Package: com.itcast.demo5.service.impl
 * Description:
 *
 * @Author MLH
 * @Create 2023/4/18 9:21
 * @Version 1.0
 */
@Service
@Transactional
public class PurseServiceImpl extends ServiceImpl<PurseMapper, Purse> implements PurseService {
    @Autowired
    private PurseLogMapper purseLogMapper;

    public Object getInfo(int id){
        QueryWrapper<Purse> queryWrapper = getPurseQueryWrapper(id);
        return getOne(queryWrapper);
    }


    public Boolean updateDecPurse(int id, BigDecimal balance, int th){
        return getDecAddBoolean(id, balance, 0, th);
    }

    @Override
    public Boolean updateAddPurse(int id, BigDecimal balance, int th) {
        return getDecAddBoolean(id, balance, 1, th);
    }

    public List<PurseLog> searchLog(int id){
        QueryWrapper<Purse> queryWrapper = getPurseQueryWrapper(id);
        Purse purse = getOne(queryWrapper);
        QueryWrapper<PurseLog> QueryWrapperLog = new QueryWrapper<>();
        QueryWrapperLog.eq("purse_id", purse.getPurseId());
        List<PurseLog> purseLogs = purseLogMapper.selectList(QueryWrapperLog);
        return purseLogs;
    }

    private Boolean getDecAddBoolean(int id, BigDecimal balance, int me, int th) {
        QueryWrapper<Purse> queryWrapper = getPurseQueryWrapper(id);
        Purse purse = getOne(queryWrapper);
        PurseLog purseLog = new PurseLog();
        purseLog.setPurseId(purse.getPurseId());
        if(me == 0){
            purse.setBalance(purse.getBalance().subtract(balance));
            purseLog.setLogDesc("用户消费" + balance + "元");
            //此处消费的第三方需要来接收金额
        }else {
            purse.setBalance(purse.getBalance().add(balance));
            purseLog.setLogDesc("收到退款" + balance + "元");
            //此处第三方需要减去相应的金额
        }
        boolean updateResult = updateById(purse);
        Date date = new Date();
        purseLog.setLogDate(new java.sql.Date(date.getTime()));
        int insertResult = purseLogMapper.insert(purseLog);
        if(updateResult == true && insertResult == 1){
            return true;
        }
        return false;
    }

    private static QueryWrapper<Purse> getPurseQueryWrapper(int id) {
        QueryWrapper<Purse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        return queryWrapper;
    }
}
